package com.kingtao.session;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: kingtao
 * @Date: 2023-08-25-14:36
 * @Description:
 */
public class SessionImpl implements Session {

    private final Map<Integer, Channel> masterChannelMap = new ConcurrentHashMap<>();
    private final Map<Channel, Integer> channelMasterMap = new ConcurrentHashMap<>();
    private final Map<Channel,Map<String,Object>> channelAttributesMap = new ConcurrentHashMap<>();

    @Override
    public void bind(Channel channel, int master) {
        masterChannelMap.put(master, channel);
        channelMasterMap.put(channel, master);
        channelAttributesMap.put(channel, new ConcurrentHashMap<>());
    }

    @Override
    public void unbind(Channel channel) {
        Integer master = channelMasterMap.remove(channel);
        masterChannelMap.remove(master);
        channelAttributesMap.remove(channel);
    }

    @Override
    public Object getAttribute(Channel channel, String master) {
        return channelAttributesMap.get(channel).get(master);
    }

    @Override
    public void setAttribute(Channel channel, String name, Object value) {
        channelAttributesMap.get(channel).put(name, value);
    }

    @Override
    public Channel getChannel(int master) {
        return masterChannelMap.get(master);
    }

    @Override
    public String toString() {
        return masterChannelMap.toString();
    }
}
